<template>
    <el-form style="padding: 10px" label-position="left" size="small" label-width="100px">
        <el-form-item label="数据源类型">
            <el-select v-model="card.cardJson.dataType" placeholder="Select">
                <el-option v-for="item in dataTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item label="编辑视图">
            <el-radio-group v-model="viewType">
                <el-radio :disabled="!isArrayType" label="table">表格</el-radio>
                <el-radio label="json">代码块</el-radio>
            </el-radio-group>
        </el-form-item>
        <div style="height: 300px;">
            <spreadsheet :value="card.cardJson.staticData" v-if="viewType === 'table' && isArrayType"
                @valueChange="sheetChange"></spreadsheet>
            <codeEditor ref="codeRef" :value="codeValue" @valueChange="codeValueChange" v-else language="json"></codeEditor>
        </div>

    </el-form>
</template>
<script setup>
import { watch, ref, computed, defineAsyncComponent } from "vue"
import { userCardStore } from '../../store/userCardStore'
const cardStore = userCardStore()
const card = computed(() => {
    return cardStore.curComponet
})
const isArrayType = computed(() => {
    return Array.isArray(card.value.cardJson.staticData)
})

const codeValue = computed(() => {
    return JSON.stringify(card.value.cardJson.staticData, null, '\t')
})
const codeRef = ref(null)

watch(card, () => {
    console.log('change card')
    codeRef.value.setValue(JSON.stringify(card.value.cardJson.staticData))
})

const spreadsheet = defineAsyncComponent(() => {
    return import('/@/pages/editor/components/spreadsheet.vue')
})

const codeEditor = defineAsyncComponent(() => {
    return import('/@/pages/editor/components/codeEditor.vue')
})

// 编辑视图
const viewType = ref(isArrayType ? 'json' : 'table')

const codeValueChange = (value) => {
    try {
        const result = JSON.parse(value)
        card.value.cardJson.staticData = result
        card.value.comData = result
    } catch (error) {

    }
}
const sheetChange = (value) => {
    card.value.cardJson.staticData = value
    card.value.comData = value
}
// 数据源类型
const dataType = ref('static')
const dataTypeOptions = ref([
    { label: '静态数据', value: 'static' }
])
</script>